import { createPersistStore, BaseState } from './index'
import { Chapter, CreateChapterParams, QuillContent } from '@/types/chapter'
import { nanoid } from 'nanoid'
import { useProjectStore } from './projectStore'

// 保存状态类型
export type SaveStatus = 'unsaved' | 'saving' | 'saved' | 'error'

interface ChapterState extends BaseState {
  chapters: Chapter[];
  currentChapter: Chapter | null;
  saveStatus: SaveStatus;
  
  // 操作函数
  fetchChapters: (projectId: string) => Promise<Chapter[]>;
  getChaptersByProject: (projectId: string) => Chapter[];
  createChapter: (params: CreateChapterParams) => Promise<Chapter>;
  updateChapter: (id: string, updates: Partial<Chapter>) => Promise<void>;
  updateChapterContent: (id: string, content: string) => Promise<void>;
  deleteChapter: (id: string) => Promise<void>;
  selectChapter: (id: string) => void;
  reorderChapters: (projectId: string, orderedIds: string[]) => Promise<void>;
  setChapters: (chapters: Chapter[]) => void;
  setCurrentChapter: (chapter: Chapter | null) => void;
  addChapter: (chapter: Chapter) => void;
  updateChapterTitle: (id: string, title: string) => void;
  setSaveStatus: (status: SaveStatus) => void;
}

// 初始状态
const initialState = {
  chapters: [],
  currentChapter: null,
  isLoading: false,
  error: null,
  saveStatus: 'unsaved' as SaveStatus
}

// 计算QuillContent或字符串的字数
const countWordsInQuillContent = (content: QuillContent | string | undefined): number => {
  // 处理undefined
  if (!content) {
    return 0;
  }
  
  // 处理字符串
  if (typeof content === 'string') {
    return content.trim().split(/\s+/).filter(Boolean).length;
  }
  
  // 处理QuillContent
  if (!content.ops || !Array.isArray(content.ops)) {
    return 0;
  }
  
  return content.ops.reduce((count, op) => {
    if (typeof op.insert === 'string') {
      return count + op.insert.trim().split(/\s+/).filter(Boolean).length;
    }
    return count;
  }, 0);
};

export const useChapterStore = createPersistStore<ChapterState>(
  'chapters',
  initialState as any,
  (set, get) => ({
    ...initialState,
    
    fetchChapters: async (projectId) => {
      set({ isLoading: true, error: null });
      
      try {
        // 在实际实现中，这里会从API或本地存储获取数据
        // 现在我们使用存储在Zustand中的数据
        // 模拟API请求延迟
        await new Promise(resolve => setTimeout(resolve, 300));
        const chapters = get().chapters.filter(c => c.projectId === projectId);
        set({ isLoading: false });
        return chapters;
      } catch (error) {
        set({ error: String(error), isLoading: false });
        throw error;
      }
    },
    
    getChaptersByProject: (projectId) => {
      return get().chapters.filter(c => c.projectId === projectId)
        .sort((a, b) => a.order - b.order);
    },
    
    createChapter: async (params) => {
      set({ isLoading: true, error: null });
      
      try {
        const { projectId } = params;
        const chapters = get().getChaptersByProject(projectId);
        const order = chapters.length > 0 
          ? Math.max(...chapters.map(c => c.order)) + 1 
          : 0;
        
        // 计算字数
        const wordCount = countWordsInQuillContent(params.content);
        
        // 创建新章节
        const now = new Date().toISOString();
        const newChapter: Chapter = {
          id: nanoid(),
          projectId,
          title: params.title,
          content: params.content || { ops: [] },
          status: params.status || 'draft',
          order,
          wordCount,
          isLocked: false,
          createdAt: now,
          updatedAt: now
        };
        
        // 更新状态
        set(state => ({ 
          chapters: [...state.chapters, newChapter],
          currentChapter: newChapter,
          isLoading: false 
        }));
        
        // 更新项目的字数统计
        const project = useProjectStore.getState().projects.find(p => p.id === projectId);
        if (project) {
          const newWordCount = project.wordCount + newChapter.wordCount;
          await useProjectStore.getState().updateProject(projectId, { 
            wordCount: newWordCount 
          });
        }
        
        return newChapter;
      } catch (error) {
        set({ error: String(error), isLoading: false });
        throw error;
      }
    },
    
    updateChapter: async (id, updates) => {
      set({ isLoading: true, error: null });
      
      try {
        const currentChapter = get().chapters.find(c => c.id === id);
        if (!currentChapter) {
          throw new Error('章节不存在');
        }
        
        // 计算新的字数
        let newWordCount = currentChapter.wordCount;
        if ('content' in updates && updates.content) {
          // 检查content类型
          const contentToCheck = typeof updates.content === 'string' 
            ? { ops: [{ insert: updates.content }] } as QuillContent 
            : updates.content;
          
          newWordCount = countWordsInQuillContent(contentToCheck);
        }
        
        // 更新章节
        set(state => {
          const chapters = state.chapters.map(c => 
            c.id === id 
              ? { 
                  ...c, 
                  ...updates, 
                  wordCount: newWordCount,
                  updatedAt: new Date().toISOString() 
                } 
              : c
          );
          
          // 如果当前选中的章节被更新，也更新currentChapter
          const currentChapter = state.currentChapter?.id === id
            ? { 
                ...state.currentChapter, 
                ...updates, 
                wordCount: newWordCount,
                updatedAt: new Date().toISOString() 
              }
            : state.currentChapter;
            
          return { chapters, currentChapter, isLoading: false };
        });
        
        // 更新项目的字数统计
        const updatedChapter = get().chapters.find(c => c.id === id);
        if (updatedChapter) {
          const projectId = updatedChapter.projectId;
          const chapters = get().getChaptersByProject(projectId);
          const totalWordCount = chapters.reduce((total, chapter) => total + chapter.wordCount, 0);
          
          await useProjectStore.getState().updateProject(projectId, { 
            wordCount: totalWordCount 
          });
        }
      } catch (error) {
        set({ error: String(error), isLoading: false });
        throw error;
      }
    },
    
    updateChapterContent: async (id, content) => {
      set({ isLoading: true, error: null });
      
      try {
        const currentChapter = get().chapters.find(c => c.id === id);
        if (!currentChapter) {
          throw new Error('章节不存在');
        }
        
        // 将HTML内容转换为QuillContent格式
        const quillContent: QuillContent = {
          ops: [{ insert: content }]
        };
        
        // 计算新的字数
        const newWordCount = countWordsInQuillContent(quillContent);
        
        // 更新章节
        set(state => {
          const chapters = state.chapters.map(c => 
            c.id === id 
              ? { 
                  ...c, 
                  content: quillContent,
                  wordCount: newWordCount,
                  updatedAt: new Date().toISOString() 
                } as Chapter
              : c
          );
          
          // 如果当前选中的章节被更新，也更新currentChapter
          const currentChapter = state.currentChapter?.id === id
            ? { 
                ...state.currentChapter, 
                content: quillContent,
                wordCount: newWordCount,
                updatedAt: new Date().toISOString() 
              } as Chapter
            : state.currentChapter;
            
          return { chapters, currentChapter, isLoading: false };
        });
        
        // 更新项目的字数统计
        const updatedChapter = get().chapters.find(c => c.id === id);
        if (updatedChapter) {
          const projectId = updatedChapter.projectId;
          const chapters = get().getChaptersByProject(projectId);
          const totalWordCount = chapters.reduce((total, chapter) => total + chapter.wordCount, 0);
          
          await useProjectStore.getState().updateProject(projectId, { 
            wordCount: totalWordCount 
          });
        }
      } catch (error) {
        set({ error: String(error), isLoading: false });
        throw error;
      }
    },
    
    deleteChapter: async (id) => {
      set({ isLoading: true, error: null });
      
      try {
        const chapterToDelete = get().chapters.find(c => c.id === id);
        if (!chapterToDelete) {
          throw new Error('章节不存在');
        }
        
        const projectId = chapterToDelete.projectId;
        
        // 删除章节
        set(state => {
          const chapters = state.chapters.filter(c => c.id !== id);
          
          // 如果删除的是当前选中的章节，重置currentChapter
          const currentChapter = state.currentChapter?.id === id
            ? null
            : state.currentChapter;
            
          return { chapters, currentChapter, isLoading: false };
        });
        
        // 更新项目的字数统计
        const chapters = get().getChaptersByProject(projectId);
        const totalWordCount = chapters.reduce((total, chapter) => total + chapter.wordCount, 0);
        
        await useProjectStore.getState().updateProject(projectId, { 
          wordCount: totalWordCount 
        });
      } catch (error) {
        set({ error: String(error), isLoading: false });
        throw error;
      }
    },
    
    selectChapter: (id) => {
      const { chapters } = get();
      const chapter = chapters.find(c => c.id === id) || null;
      set({ currentChapter: chapter });
    },
    
    reorderChapters: async (projectId, orderedIds) => {
      set({ isLoading: true, error: null });
      
      try {
        // 验证所有ID确实属于该项目
        const projectChapters = get().getChaptersByProject(projectId);
        const projectChapterIds = new Set(projectChapters.map(c => c.id));
        
        if (orderedIds.some(id => !projectChapterIds.has(id))) {
          throw new Error('无效的章节ID');
        }
        
        // 更新章节顺序
        set(state => {
          const updatedChapters = state.chapters.map(chapter => {
            if (chapter.projectId !== projectId) return chapter;
            
            const index = orderedIds.indexOf(chapter.id);
            if (index !== -1) {
              return { ...chapter, order: index };
            }
            return chapter;
          });
          
          return { chapters: updatedChapters, isLoading: false };
        });
      } catch (error) {
        set({ error: String(error), isLoading: false });
        throw error;
      }
    },
    
    setChapters: (chapters) => {
      set({ chapters });
    },
    
    setCurrentChapter: (chapter) => {
      set({ currentChapter: chapter });
    },
    
    addChapter: (chapter) => {
      set(state => ({ chapters: [...state.chapters, chapter] }));
    },
    
    updateChapterTitle: (id, title) => {
      set(state => ({
        chapters: state.chapters.map(c =>
          c.id === id ? { ...c, title } : c
        ),
        currentChapter: state.currentChapter?.id === id ? { ...state.currentChapter, title } : state.currentChapter
      }));
    },
    
    setSaveStatus: (status) => {
      set({ saveStatus: status });
    }
  })
); 